import { api } from "@/global/utils/api";
import useApiPromiseHandler from "./api-promise-handler";
import { useI18n } from "vue-i18n";
import useStaff from "./staff";

export default function useReplyModifier(replyList, replyTargetUrl) {
  const { getLocalStaff } = useStaff();
  const { t } = useI18n();
  const postReply = (reply, onSuccess, onFaild, onFinished) => {
    useApiPromiseHandler(t,
      api.post(`${replyTargetUrl}/create`, reply),
      (res) => {
        // 没有replyList代表调用者并没有维护一个评论列表，不需要相关逻辑，所以直接返回
        if (!replyList) {
          onSuccess();return;
        }
        
        // 否则构造本地的新reply的副本并加到列表中
        reply.id = res.data.id;
        // 查找并构造父reply
        if (reply.parentCommentId) {
          replyList.value.forEach(replyInList => {
            if (replyInList.id == reply.parentCommentId) {
              reply.parentReply = replyInList
              // 要把它的父评论的评论数递增（主体，也就是target的评论数递增逻辑在reply-modal中）
              replyInList.replyCount++;
            }
          })
        }
        // 填充必要字段
        let date = new Date();
        reply.postStaff = {
          avater: getLocalStaff().avater,
          name: getLocalStaff().name,
        };
        reply.createTime = date.getFullYear() + "-" +(date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
        reply.likeCount = 0;
        reply.unlikeCount = 0;
        reply.replyCount = 0;
        // 加入到列表中
        replyList.value.splice(0, 0, reply);
        // 调用成功回调
        onSuccess();
      }, onFaild, onFinished
    );
  }

  /**
   * 
   * @param replyId 删除的评论id
   * @param parentList 父列表，需要将哪些对象中的replyCount属性-1
   * @param onSuccess 
   * @param onFaild 
   */
  const handleDeleteReply = (replyId, parentList, onSuccess, onFaild) => {
    useApiPromiseHandler(t,
      api.get(`${replyTargetUrl}/delete/${replyId}`),
      () => {
        if (!replyList) {
          onSuccess();return;
        }
        let pos = -1;
        replyList.value.forEach((reply, i) => {
          if (reply.id == replyId) {
            pos = i;return;
          }
        })
        if (pos >= 0) replyList.value.splice(pos, 1);
        parentList.forEach(p => {
          p.replyCount--;
        })
        onSuccess();
      }, onFaild
    );
  }

  const handleLikeReply = (reply, onFaild) => {
    useApiPromiseHandler(t,
      api.get(`${replyTargetUrl}/like/${reply.id}`),
      () => {reply.doseILikedIt = true; reply.likeCount++;}, onFaild
    );
  }

  const handleUnlikeReply = (reply, onFaild) => {
    useApiPromiseHandler(t,
      api.get(`${replyTargetUrl}/unlike/${reply.id}`),
      () => {reply.doseILikedIt = false; reply.likeCount--;}, onFaild
    );
  }

  return { postReply, handleDeleteReply, handleLikeReply, handleUnlikeReply };
}